package com.ctgu.tengyun.util;

import com.ctgu.tengyun.bean.TokenBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

/**
 * Created by liaoweizhi on 2019/7/19.
 */
public class TokenUtil {

    @SuppressWarnings("unused")
    private static final int VERSION = 0;

    public static final int USER_ID = 1;

    public static final int USER_ROLE = 2;

    public static final int EXPIRE_TIME_INDX = 3;

    public static final String AUTH_SPLIT = "&";

    private static final Logger logger = LoggerFactory.getLogger(TokenUtil.class);

    public static final long tmp_two_month = 2L * 30 * 24 * 60 * 60 * 1000;

    public static TokenBean validatePassportToken(String token) {
        if (StringUtils.isEmpty(token)) {
            return null;
        }

        String result = RSAEncrypt.decrypt(token);
        if (StringUtils.isEmpty(result)) {
            logger.warn("result is empty, token:{}", token);
            return null;
        }
        String[] values = result.split(AUTH_SPLIT);

        long time = Long.parseLong(values[EXPIRE_TIME_INDX]);
        if (time + tmp_two_month < System.currentTimeMillis()) {
            logger.warn("result time expire, expireAtTime:{} token:{}, result:{}", new Date(time + tmp_two_month), token, result);
            return null;
        }

        long userId = Long.parseLong(values[USER_ID]);
        int roleId = Integer.parseInt(values[USER_ROLE]);

        return new TokenBean(userId, roleId, time + tmp_two_month);
    }

    public static String generatorEncryptedToken(Long userId, Integer roleId, Long expireSeconds) {
        String plain = generatorToken(userId, roleId, expireSeconds);
        return RSAEncrypt.encrypt(plain).replace("\r\n", "");
    }

    private static String generatorToken(Long userId, Integer roleId, Long expireSeconds) {

        Long expireTime = System.currentTimeMillis() + (expireSeconds * 1000);

        StringBuilder sb = new StringBuilder("v1")
                .append(AUTH_SPLIT).append(userId)
                .append(AUTH_SPLIT).append(roleId)
                .append(AUTH_SPLIT).append(expireTime);

        return sb.toString();
    }

}
